//
//  iPadSession.m
//  SCRAP_ObjC
//
//  Created by Capstone Design Fall 2010 on 11/15/10.
//  Copyright 2010 Thunderwear. All rights reserved.
//

#import "iPadSession.h"
#import "CardData.h"
#import "Player.h"
#import "BackgroundLayer.h"

// GameKit Session ID for app
#define SCRAPSessionID @"bluetooth3"

@implementation iPadSession

@synthesize gameDelegate, playerList;

- (id)init
{	
    if (self = [super init]){
		size = [[CCDirector sharedDirector] winSize];
		playerList = [[NSMutableArray alloc] initWithCapacity: 4];
	}
	
    return self;	
}

- (void)invalidateSession{
	if(gameSession != nil) {
		[gameSession disconnectFromAllPeers]; 
		gameSession.available = NO; 
		[gameSession setDataReceiveHandler: nil withContext: NULL]; 
		gameSession.delegate = nil; 
	}
}

-(void) startPicker{
	GKSession *session = [[GKSession alloc] initWithSessionID:SCRAPSessionID displayName:[[UIDevice currentDevice] name] sessionMode:GKSessionModeServer];
	session.delegate = self;
	//session.disconnectTimeout = 100;
	[session setDataReceiveHandler: self withContext:nil];
	NSLog(@"session OPEN\n\n\n\n\n\n");
	session.available = YES;
	gameSession = session;
}

- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
	gamePeerId = peerID;
	BackgroundLayer *layer = (BackgroundLayer*)gameDelegate;
	if([playerList count] < 5 && !(layer.gamePlayable || layer.cornerChoosing)){
		if([gameSession acceptConnectionFromPeer:peerID error:nil]){
			Player *newPlayer = [[Player alloc] init];
			newPlayer.name = [session displayNameForPeer:peerID];
			newPlayer.peerID = gamePeerId;
			[playerList addObject:peerID];
			[layer session:self newPlayer:newPlayer];
		}
	}
	else {
		NSLog(@"Denied Connection from peer");
		[gameSession denyConnectionFromPeer:gamePeerId];
	}
	
}

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state { 
	switch (state) {
		case GKPeerStateConnected:
			/*if ([playerList count] == 4) {
				gameSession.available = NO;
			}*/			
			break;
		case GKPeerStateDisconnected:
			NSLog(@"Disconnected!\n\n\n\n");
			BackgroundLayer *layer = (BackgroundLayer*)gameDelegate;
			NSLog(@"?%@", peerID);
			[layer removePlayerFromMenuByPeerID:peerID];
			if (gameSession.available == NO) {
				gameSession.available = YES;
			}
			break;
		default:
			break;
	}
	
}


- (void)denyConnectionFromPeer:(NSString *)peerID{
	NSLog(@"Connection Denied\n\n\n\n");
}

- (NSString *) displayNameForPeer:(NSString *)peerID
{	
    return [gameSession displayNameForPeer:peerID];	
}

- (void) sendMessage:(NSString*) msg toPeer:(NSString*)peer{
	NSData* aData;
	aData = [msg dataUsingEncoding: NSASCIIStringEncoding];
	if ([msg isEqualToString:@"StartRound"] || [msg isEqualToString:@"Ping"] ) {
		[gameSession sendDataToAllPeers:aData withDataMode:GKSendDataReliable error:nil];
	}
	else {
		NSArray *array = [NSArray arrayWithObject:peer];
		[gameSession sendData:aData toPeers:array withDataMode:GKSendDataReliable error:nil];
	}
}

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
    // Read the bytes in data and perform an application-specific action.
	NSString* aStr;
	aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	NSLog(@"Received Data from %@, %@",peer,aStr);
	[gameDelegate session:self didReceiveMessage:aStr fromPeer:peer];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

-(void) dealloc
{
	[super dealloc];
}

@end

